#include "DataBase.h"

// ----------------------------------- DataBase ----------------------------------------

namespace db
{

void DataBase::Clear()
{
    Record::Clear();
}

bool DataBase::Load(ReadStream& file)
{
    Clear();
    char dbHeader[sizeof(DB_HEADER) + 1];
    file.read(&dbHeader, sizeof(DB_HEADER));
    dbHeader[sizeof(DB_HEADER)] = 0;
    if (strcmp(dbHeader, DB_HEADER) == 0)
    {
        u16 dbVersion;
        file.read(&dbVersion, sizeof(dbVersion));
        if (dbVersion == DB_VERSION)
        {
            Record::Load(file);
        }
    }
    file.complete();
    return false;
}

bool DataBase::Save(WriteStream& file)
{
    file.write(DB_HEADER, sizeof(DB_HEADER));
    file.write(&DB_VERSION, sizeof(DB_VERSION));
    Record::Save(file);
    file.complete();
    return true;
}

bool DataBase::LoadFromFile(const std::string& fileName, bool decompress)
{
    ReadFileStream stream(fileName);
    if (!stream.open()) return false;
#ifdef _DB_USE_ZLIB
    if (decompress)
        return Load(ReadCompressedStream(stream));
    else
#endif
    return Load(stream);
}

bool DataBase::SaveToFile(const std::string& fileName, bool compress)
{
    WriteFileStream stream(fileName);
    if (!stream.open()) return false;
#ifdef _DB_USE_ZLIB
    if (compress)
        return Save(WriteCompressedStream(stream));
    else
#endif
    return Save(stream);
}


DataBase::DataBase() :
    Record(RC_NAMEDCHILD)
{
	//
}

};